<?php

namespace App\Admin\Actions\Modal;

use App\Admin\Actions\Form\DeviceForm;
use Dcat\Admin\Admin;
use Dcat\Admin\Grid\Tools\AbstractTool;
use Dcat\Admin\Traits\HasPermissions;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use App\Models\Device;
use App\Models\ProjectUser;
use Illuminate\Support\Facades\Cache;
use Illuminate\Http\Request;



class SmokeRegister extends AbstractTool
{
    /**
     * @return string
     */
    protected $title = '设备注册';

    public function handle(Request $request) 
    {
        $this->response()->script(
            <<<JS
            Dcat.loading({
                color: Dcat.color.primary,
            }); 
        JS    
        );
        if(!Cache::has('authtoken')){
            authentication();
        }
        $project = ProjectUser::where(['user_id'=>Admin::user()->id])->pluck('projectId')->toArray();
        $device = Device::whereIn('projectId',$project)->where(['device_type'=>1,'status'=>0])->get()->toArray();
        foreach($device as $val){
            $imei = $val['cid'];
            $dtype = 'GDHS90BWNB';
            $manu = 'Hisense';
            $devicetype = 'Smoke';
            $url = 'https://device.api.ct10649.com:8743/iocm/app/reg/v1.1.0/deviceCredentials?appId=86y97uYn78Try5i1zFdTLiErnX4a';
            $header = array('Content-Type:application/json','Authorization:Bearer '.Cache::get('authtoken'),'app_key:86y97uYn78Try5i1zFdTLiErnX4a');
            $data = '{"verifyCode":"'.$imei.'","nodeId":"'.$imei.'","deviceInfo":{"manufacturerId":"'.$manu.'","manufacturerName":"'.$manu.'","deviceType":"'.$devicetype.'","model":"'.$dtype.'","protocolType":"CoAP"}}';
            $curl = curl_init(); // 启动一个CURL会话
            curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
            curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false); // 对认证证书来源的检查
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);// 从证书中检查SSL加密算法是否存在
            curl_setopt($curl, CURLOPT_SSLCERT,dirname(dirname(dirname(dirname(__FILE__)))).'/server.crt');
            curl_setopt($curl, CURLOPT_SSLKEY, dirname(dirname(dirname(dirname(__FILE__)))).'/server.key');
            curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
            curl_setopt($curl, CURLOPT_HTTPHEADER, $header); // 显示返回的Header区域内容
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
            $res = curl_exec($curl); // 执行操作
            $ret = ['status' => 1];
            if ($error = curl_errno($curl)) {
                $ret['status'] = 0;
                $ret['return'] = $error;
            } else {
                $ret['return'] = $res;
            }
            curl_close($curl); // 关闭CURL会话
            $res = json_decode($ret['return'],1);   
            if($ret['status']==1){
                if(!isset($res['error_code'])){
                    Device::where(['cid'=>$res['verifyCode']])->update(['gatewayId'=>$res['deviceId']]);
                }
            }
        }
        $this->response()->script(
            <<<JS
            Dcat.loading(false);
        JS    
        );
        return $this->response()->success('注册完成！');
    }

    //鉴权
    // public function authentication(){
    //     $data = 'appId=86y97uYn78Try5i1zFdTLiErnX4a&secret=aayy3kB2YJGh1FCpeyxGsyC_uCAa';
    //     $url = 'https://device.api.ct10649.com:8743/iocm/app/sec/v1.1.0/login';
    //     $header = ["Content-Type" => "application/x-www-form-urlencoded;"];//貌似不需要,默认就是
    //     $a = $this->postSsl($url,$data,$header);
    //     if($a['status']==1){
    //         $return = json_decode($a['return'],1);
    //         Cache::add('authtoken', $return['accessToken'], 3000);
    //     }
    // }
    // public function postSsl($url, $data, $header) {
    //     //if (is_array($data)) {
    //     //    $data = http_build_query($data);
    //     //}
    //     $curl = curl_init(); // 启动一个CURL会话
    //     curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
    //     curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false); // 对认证证书来源的检查
    //     curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);// 从证书中检查SSL加密算法是否存在
    //     curl_setopt($curl, CURLOPT_SSLCERT,dirname(dirname(dirname(dirname(__FILE__)))).'/server.crt');
    //     curl_setopt($curl, CURLOPT_SSLKEY, dirname(dirname(dirname(dirname(__FILE__)))).'/server.key');
    //     curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
    //     curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
    //     curl_setopt($curl, CURLOPT_HTTPHEADER, $header); // 显示返回的Header区域内容
    //     curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
    //     $res = curl_exec($curl); // 执行操作
    //     $ret = ['status' => 1];
    //     if ($error = curl_errno($curl)) {
    //         $ret['status'] = 0;
    //         $ret['return'] = $error;
    //     } else {
    //         $ret['return'] = $res;
    //     }
    //     curl_close($curl); // 关闭CURL会话
    //     return $ret; // 返回数据
    // }
    
}